<template>
  <div ref="chart" class="chart" :style="style"></div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  nextTick,
  getCurrentInstance,
  toRefs,
  toRaw,
  onMounted,
} from "vue";

// 接收值
const props = defineProps({
  options: {
    type: Object,
    default: () => {},
  },
});

const { options } = toRefs(props);

// 定义值
const chart = ref();
const style = reactive({
  width: "100%",
  height: "420px",
  background: "#f8f8f8",
  borderRadius: "8px",
});

const instance = getCurrentInstance();
const echarts = instance?.appContext.config.globalProperties.$echarts;

const optionList = reactive({
  title: {
    text: "",
  },
  backgroundColor: "#FFFFFF",
  tooltip: {
    trigger: "axis",
  },
  legend: {},
  grid: {
    left: "0%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    axisTick: {
      alignWithLabel: true,
    },
  },
  yAxis: {
    type: "value",
    name: "单位：分",
  },
  dataset: {
    source: [],
  },
  series: [],
});

// 定义加载函数
const initCharts = () => {
  if (!options.value) return;
  optionList.series = options.value.series;
  optionList.yAxis.name = options.value.yAxisName;
  optionList.title.text = options.value.title;
  optionList.dataset.source = options.value.source;
  let myChart = echarts.init(chart.value);
  myChart.setOption(optionList);
  window.addEventListener("resize", () => {
    myChart.resize();
  });
};

// 监听当配置项发生变化的时候，调用加载函数
watch(
  () => props.options,
  (val) => {
    nextTick(() => {
      initCharts();
    });
  },
  { immediate: true }
);

onMounted(() => {
  initCharts();
});
</script>

<style lang="less" scoped></style>
